package com.roc.service.area;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.roc.bean.AreaBean;
import com.roc.dao.DaoException;
import com.roc.dao.IBaseDao;
import com.roc.dao.ISQLBaseDao;
import com.roc.newPage.IPageDao;
import com.roc.pojo.Operators;
import com.roc.pojo.TblArea;
import com.roc.pojo.TblInsInf;
import com.roc.service.ServiceException;
import com.roc.util.Constance;
import com.roc.util.constant.Role;
import com.roc.util.constant.SysLogType;
@Service
@Transactional
public class AreaServiceImpl implements  IAreaService{

	static Logger logger=Logger.getLogger(AreaServiceImpl.class);

	@Autowired
	private IBaseDao baseDao;
	@Autowired
	private ISQLBaseDao sqlBaseDao;
	@Autowired
	private IPageDao pageDao;
	
	
	@Override
	public boolean addAreaList(AreaBean area, Operators op) throws ServiceException {
		// TODO Auto-generated method stu
		
		String sql =" SELECT COUNT(1) FROM TBL_AREA WHERE INS_CODE=? AND NAME =? ";
		List<Object>  params = new ArrayList<Object>();
		String[] parma = {area.getInsCode(),area.getName()};
		params.add(area.getInsCode());
		params.add(area.getName());
		try {
			Object r = pageDao.findObj(sql, parma);
			long count = Long.parseLong(r.toString());
			if(count>0){
				return false;
			}else{
				TblArea   are  = new TblArea();
				are.setInsCode(area.getInsCode());
				are.setName(area.getName());
				are.setRemark1(area.getRemark1());
				are.setCrtDt(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
				are.setStatus(area.getStatus());
			     baseDao.editSave(are);
				logger.info("添加【"+"机构"+area.getInsCode()+"下区域"+area.getName()+"】成功!");
				baseDao.addSyslog(SysLogType.BLACK_ADD.getCode(), SysLogType.BLACK_ADD.getName(), op.getAccountNo(), op.getAccountNo()+"添加【"+"机构"+area.getInsCode()+"下区域"+area.getName()+"】成功");
				
			}
		} catch (DaoException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.debug(e.getMessage(), e);
			throw new ServiceException("插入区域失败！！");
		
		}
		return true;
	}
	/**
	 * 验证是否存在
	 * @see com.roc.service.area.IAreaService#findByAreaNum(java.lang.String)
	 * @Title: findByAreaNum
	 * @Description:TODO(...)
	 * @param areaNum
	 * @return
	 * @throws ServiceException
	 * @author JD
	 * @date: 2017年8月7日 下午3:50:20
	 *
	 */
	@Override
	public AreaBean findByAreaNum(String id) throws ServiceException {
		String sql="SELECT   t.id, t.ins_code,t.name,(SELECT i.ins_name  FROM tbl_ins_inf  i WHERE i.INS_ID_CD=t.ins_code  AND i.ins_type='1') ins_name,t.status , t.CRT_DT ,t.REMARK1 from tbl_area t  WHERE t.id=? ";
		Object[] parmas={id};
		AreaBean area=null;
		try {
			Object object=sqlBaseDao.findObj(sql, parmas);
			if(object!=null)
			{
				Object[] obj=(Object[]) object;
				area=new AreaBean();
				area.setId(Constance.Null2EmptyTrim(obj[0]));
				area.setInsCode(Constance.Null2EmptyTrim(obj[1]));
				area.setName(Constance.Null2EmptyTrim(obj[2]));
				area.setInsName(Constance.Null2EmptyTrim(obj[3]));
				area.setStatus(Constance.Null2EmptyTrim(obj[4]));
				area.setCrtDt(Constance.Null2EmptyTrim(obj[5]));
				area.setRemark1(Constance.Null2EmptyTrim(obj[6]));
			}
		} catch (DaoException e) {
			logger.debug(e.getMessage(),e);
			throw new ServiceException("查询区域id为【"+id+"】失败");
		}
		return area;
	}

	@Override
	public int updateAreaList(AreaBean area, Operators op)
			throws ServiceException {
		String sql=" UPDATE  tbl_area t SET  t.REMARK1=?,  t.name=?,  t.ins_code=?, t.status=? , t.crt_dt=?  WHERE t.ID=? ";
		int effect=0;
		List<Object> parmas=new ArrayList<Object>();
		parmas.add(area.getRemark1());
		parmas.add(area.getName());
		parmas.add(area.getInsCode());
		parmas.add(area.getStatus());	
		parmas.add(area.getCrtDt());
		parmas.add(area.getId());
		try {
			effect=sqlBaseDao.deleteBySql(sql, parmas);
			if(effect>0)
			{
				logger.info("更改【"+"机构"+area.getInsCode()+"下区域"+area.getName()+"】成功!");		
				baseDao.addSyslog(SysLogType.UPDATE_AREA.getCode(), SysLogType.UPDATE_AREA.getName(), op.getAccountNo(), op.getAccountNo()+"更改【"+"机构"+area.getInsCode()+"下区域"+area.getName()+"】成功");
			}
		} catch (DaoException e) {
			logger.debug(e.getMessage(),e);
			throw new ServiceException("更改区域信息失败");
		}
		return effect;
	}
	@Override
	public List<TblInsInf> queryInsInf(Operators op) throws ServiceException {
		
		 List<TblInsInf> orgCodeList = new ArrayList<TblInsInf>();
			try {
				String sql="";
				if(op.getRoleType().equals(Role.SYSTEM.getCode())){
					sql=" SELECT  t.INS_ID_CD,t.ins_name FROM  tbl_ins_inf  t  WHERE   t.ins_id_cd  is not null  AND t.ins_type='1'  ";
				}else
				 sql=" SELECT  t.INS_ID_CD,t.ins_name FROM  tbl_ins_inf  t  WHERE   t.ins_id_cd = '" + op.getOrgCode() + "'  AND t.ins_type='1'  ";
				List<?> lists = sqlBaseDao.queryAll(sql);
				
	          if(null != lists && lists.size() > 0){
	        	  Iterator iterator=lists.iterator();
	        	  while (iterator.hasNext()) {
						Object[] obj=(Object[]) iterator.next();
						TblInsInf exp=new TblInsInf();
						exp.setInsIdCd(Constance.Null2EmptyTrim(obj[0]));
						exp.setInsName(Constance.Null2EmptyTrim(obj[1]));
						orgCodeList.add(exp);
				}
				}
			} catch (Exception e) {
				e.printStackTrace();
				logger.error("加载机构失败", e);
			}	
			return orgCodeList;
		}
	
	/**
	 * 验证区域名称是否存在
	 * @see com.roc.service.area.IAreaService#isExistName(java.lang.String, java.lang.String)
	 *
	 * @Title: isExistName
	 * @Description:TODO(...)
	 * @param id
	 * @param name
	 * @param insCode
	 * @return
	 * @author JD
	 * @date: 2017年8月10日 下午5:43:38
	 *
	 */
	@Override
	public boolean isExistName(AreaBean area) {
		// TODO Auto-generated method stub
		
		
		   
		StringBuilder sql = new StringBuilder(" select count(ID) from tbl_area where name = ? and INS_CODE = ? ");
		List<Object> params = new ArrayList<Object>();
		params.add(area.getName());
		params.add(area.getInsCode());
		
		if (StringUtils.isNotEmpty(area.getId())) {
			sql.append(" and ID != ? ");
			params.add(area.getId());
		}
		try {
			List<Object> list = sqlBaseDao.queryAll(sql.toString(), params.toArray());
			
			
			if (list != null && !list.isEmpty()) {
				BigDecimal result = (BigDecimal) list.get(0);
				if (result.intValue() > 0)
					return false;
			}
		} catch (DaoException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return true;
	}
	/**
	 * 验证区域编码是否存在
	 * @see com.roc.service.area.IAreaService#isExistAreaCode(com.roc.bean.AreaBean)
	 *
	 * @Title: isExistAreaCode
	 * @Description:TODO(...)
	 * @param area
	 * @return
	 * @author JD
	 * @date: 2017年8月19日 下午3:42:35
	 *
	 */
	@Override
	public boolean isExistAreaCode(AreaBean area) {
		// TODO Auto-generated method stub
		StringBuilder re_sql = new StringBuilder(" SELECT COUNT(ID) FROM   tbl_area  T  WHERE  INS_CODE = ? and  T.REMARK1=? " );
		
		   List<Object> re_params = new ArrayList<Object>();
		   re_params.add(area.getInsCode());
		   re_params.add(area.getRemark1());
		   
		   if (StringUtils.isNotEmpty(area.getId())) {
			   re_sql.append(" and ID != ? ");
			   re_params.add(area.getId());
			}
		   
		   try {
			List<Object> re_list = sqlBaseDao.queryAll(re_sql.toString(), re_params.toArray());
			if (re_list != null && !re_list.isEmpty()) {
				BigDecimal res = (BigDecimal) re_list.get(0);
				if (res.intValue()>0)
					return false;
			}
			
		} catch (DaoException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return true;
	}
	/**
	 * 查询所有区域
	 */
	@Override
	public List<AreaBean> queryAreaInf(Operators op) throws ServiceException {
		
		 List<AreaBean> areaCodeList = new ArrayList<AreaBean>();
			try {
				String sql="";
				 sql=" SELECT  t.id,t.name FROM  tbl_area  t  WHERE   t.status='1'  and t.ins_code='48502000'";
				List<?> lists = sqlBaseDao.queryAll(sql);
				
	          if(null != lists && lists.size() > 0){
	        	  Iterator iterator=lists.iterator();
	        	  while (iterator.hasNext()) {
						Object[] obj=(Object[]) iterator.next();
						AreaBean exp=new AreaBean();
						exp.setId(Constance.Null2EmptyTrim(obj[0]));
						exp.setName(Constance.Null2EmptyTrim(obj[1]));
						areaCodeList.add(exp);
				}
				}
			} catch (Exception e) {
				e.printStackTrace();
				logger.error("加载区域失败", e);
			}	
			return areaCodeList;
		}
	
	/**
	 * 查询所有区域
	 */
	@Override
	public List<AreaBean> queryAreaInfByOp(Operators op) throws ServiceException {
		
		 List<AreaBean> areaCodeList = new ArrayList<AreaBean>();
			try {
				String sql="";
				
				if(op.getRoleType().equals(Role.SYSTEM.getCode())){
					 sql=" SELECT  t.id,t.name FROM  tbl_area  t  WHERE   t.status='1'  and t.ins_code='48502000'";
				}else{
					sql=" SELECT  t.id,t.name FROM  tbl_area  t  WHERE   t.status='1'  and t.ins_code='48502000' and t.id="+op.getCompanyid();
				}
				 List<?> lists = sqlBaseDao.queryAll(sql);
				
	          if(null != lists && lists.size() > 0){
	        	  Iterator iterator=lists.iterator();
	        	  while (iterator.hasNext()) {
						Object[] obj=(Object[]) iterator.next();
						AreaBean exp=new AreaBean();
						exp.setId(Constance.Null2EmptyTrim(obj[0]));
						exp.setName(Constance.Null2EmptyTrim(obj[1]));
						areaCodeList.add(exp);
				}
				}
			} catch (Exception e) {
				e.printStackTrace();
				logger.error("加载区域失败", e);
			}	
			return areaCodeList;
		}
	
	@Override
	public List<AreaBean> queryAllAreaInf() throws ServiceException {

		 List<AreaBean> areaCodeList = new ArrayList<AreaBean>();
			try {
				String sql="";
				 sql=" SELECT  t.id,t.name FROM  tbl_area  t  WHERE   t.status='1'  and t.ins_code='48502000'";
				List<?> lists = sqlBaseDao.queryAll(sql);
				
	          if(null != lists && lists.size() > 0){
	        	  Iterator iterator=lists.iterator();
	        	  while (iterator.hasNext()) {
						Object[] obj=(Object[]) iterator.next();
						AreaBean exp=new AreaBean();
						exp.setId(Constance.Null2EmptyTrim(obj[0]));
						exp.setName(Constance.Null2EmptyTrim(obj[1]));
						areaCodeList.add(exp);
				}
				}
			} catch (Exception e) {
				e.printStackTrace();
				logger.error("加载区域失败", e);
			}	
			return areaCodeList;
	}

}
